package top.huntwolf.admin.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.huntwolf.admin.common.enums.CodeMsg;
import top.huntwolf.admin.dao.AddressDao;
import top.huntwolf.admin.exception.ServiceException;
import top.huntwolf.admin.pojo.Address;
import top.huntwolf.admin.utils.TokenUtil;

import java.util.List;

@Service
@Transactional
public class AddressService {

    @Autowired
    private AddressDao addressDao;

    public void insert(Address address){
        address.setOpenId(TokenUtil.getTokenOpenId());
        if(addressDao.selectDuplicate(address)!=null){
            throw new ServiceException(CodeMsg.DUPLICATE_ADDRESS.fillArgs("地址已存在"));
        }
        if(address.isPrimary()){
            List<Address> addresses = addressDao.selectAllByUser(TokenUtil.getTokenOpenId());

            for(Address address1 : addresses){
                address1.setPrimary(false);
                addressDao.update(address1);
            }

        }
        addressDao.insert(address);

    }

    public void delete(Integer addressId){

        Address address = addressDao.selectById(addressId);
        address.setDelete(true);
        addressDao.update(address);

    }

    public List<Address> select(){

        return addressDao.selectAllByUser(TokenUtil.getTokenOpenId());

    }

    public void update(Address address){

        if(address.isPrimary()){
            List<Address> addresses = addressDao.selectAllByUser(TokenUtil.getTokenOpenId());

           for(Address address1 : addresses){
               address1.setPrimary(false);
               addressDao.update(address1);
           }

        }
        Address beforeAd = new Address().setAddressId(address.getAddressId()).setDelete(true);
        addressDao.update(beforeAd);
        addressDao.insert(address);

    }

    public Address selectById(int id){
        return addressDao.selectById(id);

    }

}
